#!/usr/bin/env python3
import sys
from openpyxl import Workbook

def save_to_xlsx(data, filename="output.xlsx"):
    """
    将二维数据（包含表头）保存为 XLSX 文件。

    参数：
        data (list[list]): 例如 [["name","age"],["Alice",20],["Bob",25]]
        filename (str): 保存的文件名，默认 output.xlsx
    """
    # 检查 data 是否有效
    if not data or not isinstance(data, list):
        raise ValueError("data 必须是包含行数据的二维列表")

    wb = Workbook()
    ws = wb.active

    # 写入数据
    for row in data:
        ws.append(row)

    # 保存文件
    wb.save(filename)
    print(f"文件已保存: {filename}")


def merge_by_first_column(table1, table2):
    """
    基于第一列值将两个表合并（类似 left join）。
    假设两个表都有表头且第一列为主键。

    参数:
        table1, table2: list[list] 格式的数据表

    返回:
        一个新的合并表，同样包含表头
    """

    # 表头处理
    header1 = table1[0]
    header2 = table2[0][1:]  # 去掉重复的第一列
    result = [header1 + header2]

    # 将table2转成字典方便查找
    lookup = {row[0]: row[1:] for row in table2[1:]}

    # 遍历table1数据，合并table2匹配项
    for row in table1[1:]:
        key = row[0]
        extra = lookup.get(key, [""] * (len(header2)))  # 如果没有匹配，用空字段填充
        result.append(row + extra)

    return result


def main():
    if len(sys.argv) != 3:
        print("Usage: create-snapshot.py <status_file> <json2csv_file>")
        sys.exit(1)
    status_file = sys.argv[1]
    json2csv_file = sys.argv[2]
    
    status_table = [
        ['路径', '当前状态']
    ]
    with open(status_file, 'r') as sf:
        for line in sf:
            line = line.strip()
            if not line:
                continue
            path, owners = line.split('\t')
            path = path.strip()
            owners = owners.strip()
            status_table.append([path, owners])
    
    json2csv_table = [
        ['路径', '修正前']
    ]
    with open(json2csv_file, 'r') as cf:
        for line in cf:
            line = line.strip()
            if not line:
                continue
            parts = line.split('\t')
            path = parts[0].strip()
            owners = parts[1].strip() if len(parts) > 1 else ""
            json2csv_table.append([path, owners])
    
    data = merge_by_first_column(status_table, json2csv_table)
    save_to_xlsx(data, filename="committers-snapshot.xlsx")


if __name__ == "__main__":  
    main()
